import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCDemo3 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入id");
        int studentId = scanner.nextInt();


        DataSource dataSource = new MysqlDataSource();//向上转型
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java14?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("808250");

        Connection connection = dataSource.getConnection();

        String sql = "select * from student where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, studentId);

        //执行查询操作,要使用executeQuery,返回值是一个ResultSet类型的对象,表示一个表格
        ResultSet resultSet =statement.executeQuery();

        //遍历结果集合
        while (resultSet.next()){
            //获取这一行的学号列
            int id = resultSet.getInt("id");
            //获取姓名列
            String name = resultSet.getString("name");
            System.out.println("id: "+ id +", name: " + name);
        }

        resultSet.close();
        statement.close();
        connection.close();
    }
}
